package com.hao.elasticsearch.service;

import com.alibaba.fastjson.JSON;
import com.hao.elasticsearch.entity.Content;
import com.hao.elasticsearch.utils.HtmlPaseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: 苦逼程序员
 **/
@Service
public class ContentService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    //解析数据，放入到es 索引库中
    public Boolean paseContent(String keywords)throws Exception{
        //解析查询数据
        List<Content> list = new HtmlPaseUtils().paseJD(keywords);
        //将查询到的数据批量放入到索引库中
        BulkRequest bulkRequest = new BulkRequest();

            for (int i = 0; i < list.size(); i++) {
                bulkRequest.add(
                        new IndexRequest("jd_index")
                                .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
            }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
           return !bulk.hasFailures();
    }
    //获取索引库中的信息
    public List<Map<String,Object>> searchPage(String keywords,int pageNo,int pageSize)throws Exception{
        if (pageNo <1){
            pageNo=1;
        }
           if (pageSize==0){
            pageSize=10;
        }
        //创建获取请求
        SearchRequest jd_index = new SearchRequest("jd_index");

        //构造查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //精准查询
        TermQueryBuilder title = QueryBuilders.termQuery("title", keywords);
        sourceBuilder.query(title);
        //设置分页参数
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        jd_index.source(sourceBuilder);

        SearchResponse search = restHighLevelClient.search(jd_index, RequestOptions.DEFAULT);
        //把查询到的数据封装到集合中
       List<Map<String, Object>> list=new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }
     //获取索引库中的信息进行高亮显示
    public List<Map<String,Object>> searchPageHight(String keywords,int pageNo,int pageSize)throws Exception{
        if (pageNo <1){
            pageNo=1;
        }
           if (pageSize==0){
            pageSize=10;
        }
        //创建获取请求
        SearchRequest jd_index = new SearchRequest("jd_index");

        //构造查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //精准查询
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("title", keywords);
        sourceBuilder.query(queryBuilder);
        //设置分页参数
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false); //一个标题中有多个关键字，只显示一个高亮
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        jd_index.source(sourceBuilder);

        SearchResponse search = restHighLevelClient.search(jd_index, RequestOptions.DEFAULT);
        //把查询到的数据封装到集合中
       List<Map<String, Object>> list=new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            //获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");

            //这是原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            //解析高亮的字段,将原来的字段换为我们高亮的字段即可
            Text[] fragments = title.getFragments();
            String n_title="";
            if (fragments != null) {
                for (Text fragment : fragments) {
                    n_title += fragment;
                }
                sourceAsMap.put("title", n_title); //高亮字段替换掉原来的字段即可
            }
            list.add(sourceAsMap);
        }
        return list;
    }

}
